package lab03.test06;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.CollationKey;
import java.text.Collator;
import java.util.*;

public class Test06 {

    public static void main(String[] args) {
        String path = "E:\\word.txt";
        RandomAccessFile file = null;

        Map<String, Integer> map = new HashMap();
        StringBuffer stringBuffer = new StringBuffer();
        String line = null;

        try {

            file = new RandomAccessFile(path, "rw");

            while ((line = file.readLine()) != null) {

                stringBuffer.append(line);


                //map
                //key        value
                //hello         2
                //study         2
                //先判断map中有没有这个key,没有直接将value赋值为1
//                if (map.get(line)==null){
//
//                    map.put(line,1);
//                }else {
//
//                   int value=map.get(line);
//                   value=value+1;
//                   map.put(line,value);
//                   //一行代码：map.put(line,map.get(line)+1)
//
//                }


            }
            String str = stringBuffer.toString();
            String words[] = str.split("[^a-zA-Z]");

            System.out.println("一共出现了" + words.length + "个单词");

            for (int i = 0; i < words.length; i++) {

                if (map.get(words[i]) == null) {

                    map.put(words[i], 1);
                } else {

                    map.put(words[i], map.get(words[i]) + 1);
                }
            }



            System.out.println("一共出现了" + map.size() + "个不同的单词");

            List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());

            //comparator是选择器接口，可用于比较
            Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
                @Override
                public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
                    return o1.getValue().compareTo(o2.getValue());
                }
            });

            for (Map.Entry<String, Integer> entry : list) {
                if (entry.getKey() != "") {
                    System.out.println("单词" + entry.getKey() + "出现了:" + entry.getValue() + "次");
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                file.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

